<?php

namespace app\index\controller;

use app\index\model\Address;
use app\index\model\Comments;
use app\index\model\Order;
use app\index\model\OrderNum;
use app\index\model\Regions;
use app\index\model\ShopCart;
use think\Controller;
use think\Db;
use think\Request;
use think\View;

class User extends Base
{
    /**
     * 订单（完成）
     */

    public function order()
    {

        $uid = session('uid');
//        $order = ShopCart::get([
//            'user_id', $uid
//        ]);
//        $order = new  ShopCart();
//        dump($order->address);die;
//        $order = ShopCart::where('shop_cart.user_id', $uid)
//                        ->with('orderNum')
//                        ->with('goods')
//                        ->select();
//        $order1 = $order->address()
////                        ->with('orderNum')
//        ->where('address.user_id', $uid)
//        ->getData();

//        $aa=Db::table('shop_cart')->field(['id'=>'shop_id'])->select();

        $order = ShopCart::join('goods', 'goods.id=shop_cart.goods_id')
            ->join('order_num', 'order_num.id=shop_cart.order_id')
            ->join('address', 'address.id=order_num.address_id')
            ->where('shop_cart.user_id', $uid)
            ->field(['goods.goods_name', 'address.address_name', 'address.recipient',
                'order_num.*', 'shop_cart.*', 'shop_cart.id' => 'shop_cart_id'])
            ->select();
//        return jj($order);
//dd($order);

        $order1 = OrderNum::where('user_id', $uid)->select();
        $cancelNum = $noPay = $payNum = 0;
        for ($i = 0; $i < count($order1); $i++) {

            if ($order1[$i]['status'] === 0)//已付款
                $payNum++;
            else if ($order1[$i]['status'] === 1)  //未付款
                $noPay++;
            else                            //取消订单
                $cancelNum++;
        }
        $event = \think\Loader::controller('Goods', 'widget');
        $shopCart = $event->topHeader();

        //获取分类
        $result = Db('type')
            ->where("pid=0")
            ->limit(2)
            ->select();
        $type = $this->getType($result);
        View::share('type', $type);
//        dd($cancelNum);
//        dump($order);
//        dd($order1);
//        dump($order[0]['user']->id);
        $this->assign([
            'order' => $order,
            'noPay' => $noPay,
            'payNum' => $payNum,
            'cancelNum' => $cancelNum,
            "shopCart" => $shopCart
        ]);
        return $this->fetch();
    }

    /**
     * 获取分类
     */
    public function getType($type)
    {
        $m = Db('type');
//        $type=$m->where("pid=0")->select();//获取一级分类
        $type2 = array();
        $type3 = array();

        foreach ($type as $key => $value) {
            $type[$key]['child'] = array();//二级分类的名字
            $type2 = $m->where("pid=" . $value['id'])->select();//获取二级分类

            foreach ($type2 as $k => $v) {

                array_push($type[$key]['child'], $v);//合并一级与二级分类
                $type[$key]['child'][$k]['child2'] = array();////三级分类的名字

                $type3 = $m->where("pid=" . $v['id'])->select();//获取三级分类
                foreach ($type3 as $v2) {
                    $v2['goods'] = \app\index\model\Goods::where('type_id', $v2['id'])->join('attribute', 'goods.id=attribute.goods_id')
                        ->group('goods.id')->SELECT();
                    array_push($type[$key]['child'][$k]['child2'], $v2);//合并一级二级三级分类

                }


            }

        }
        return $type;
    }

    /**
     * 订单删除（完成）
     */
    public function orderDel()
    {
        $id = input('id');

        $del = ShopCart::where('order_id', '<>', '')
            ->where('id', $id)
            ->delete();

        if ($del) {
            $this->success('删除成功');
        } else {
            $this->success('删除失败');
        }


    }

    /**
     *我的购物车(完成)
     */
    public function shopCart()
    {
        $id = session('uid');
        $cart = new ShopCart();
        $cart1 = ShopCart:: where(['user_id' => $id,
            'order_id' => null])->with('goods')->select();


        cache('count' . session('uid'), count($cart1));
        $sum = 0;
        for ($i = 0; $i < count($cart1); $i++) {
            $sum += $cart1[$i]['price'] * $cart1[$i]['num'];
            cache('shopCart' . $i . session('uid'), $cart1[$i]['id']);
        }

        //获取分类
        $result = Db('type')
            ->where("pid=0")
            ->limit(2)
            ->select();
        $type = $this->getType($result);
        View::share('type', $type);

        cache('sum_price' . session('uid'), $sum);
//      dump($cart1);
//        dd($sum);
//        exit();
        $this->assign(['cart' => $cart1,
            'sum' => $sum
        ]);
        return $this->fetch();
    }

    /**
     * 购物车物品删除(完成)
     */
    public function cartDel()
    {
        $id = input('id');
        if ($id) {

            $res = ShopCart::destroy($id);
            if ($res) {
                $this->success('删除成功');
            } else {
                $this->success('删除失败');
            }
        } else {
            $this->error('未知错误');
        }
    }

    /**
     * 更新购物车页面信息(完成)
     */
    public function updateCart()
    {
//        session('Amount',$_POST['amount'][0]);
        session('goodsId', $_POST['id']);


        $Amount = $_POST['amount'];
        $Id = $_POST['id'];
//
//        session('Amount',$Amount);
//        die;
        cache('count' . session('uid'), count($Id));
        for ($i = 0; $i < count($Amount); $i++) {

            ShopCart::where('id', $Id[$i])->update(['num' => $Amount[$i]]);
            cache('shopCart' . $i . session('uid'), $Id[$i]);
        }
    }

    /**
     * 核对订单
     */
    public function checkOrder()
    {
        //收货人
        $address = Address::where(['user_id' => session('uid'),
            'type' => 1])->with('User')->find();
//dd($address);
        cache('address_id' . session('uid'), $address);
        $addresses = Address::where(['user_id' => session('uid')])
            ->with('User')->select();

//dd($addresses);
        //购物车
        $shopCart = shopCart::where(['user_id' => session('uid'),
            'order_id' => null])
            ->join('goods', 'shop_cart.goods_id=goods.id')
            ->select();


        //一级行政区 省
        $province = Regions::where('father_id', null)->select();
//dd($province);
        $sum = $total = 0;

        //获取分类
        $result = Db('type')
            ->where("pid=0")
            ->limit(2)
            ->select();
        $type = $this->getType($result);
        View::share('type', $type);

        for ($i = 0; $i < count($shopCart); $i++) {
            $sum += $shopCart[$i]['price'] * $shopCart[$i]['num'];
            $total += $shopCart[$i]['num'];
        }
        cache("sum" . session('uid'), $sum);

        $this->assign(['shopCart' => $shopCart,
            'sum' => $sum,
            'total' => $total,
            'address' => $address,
            'addresses' => $addresses,
            'province' => $province]);
        return $this->fetch();
    }

    /**
     * 成功提交订单
     */
    public function submitOrder()
    {

        $id = input('id');
//        dd($id);
        $arr = [];
//        dd(cache('count'.session('uid')));
        for ($i = 0; $i < cache('count' . session('uid')); $i++) {
            array_push($arr, cache('shopCart' . $i . session('uid')));  //order表物品id
        }

        $order = new ShopCart;

        for ($i = 0; $i < count($arr); $i++) {
            $res = $order->where('id', $arr[$i])
                ->update([
                    'order_id' => $id
                ]);
        }
//        dd($list);

//        dd($res);
        if ($res) {
            return view();
        } else {
            return $this->error('失败');
        }


    }

    /**
     * 用户信息
     */
    public function user()
    {
        $uid = session('uid');
        $users = new \app\index\model\User();
        $user = $users->find($uid);

        $event = \think\Loader::controller('Goods', 'widget');
        $shopCart = $event->topHeader();
        //获取分类
        $result = Db('type')
            ->where("pid=0")
            ->limit(2)
            ->select();
        $type = $this->getType($result);
        View::share('type', $type);
//    dump($user);die;
//    return view();
        $this->assign(['user' => $user,
            "shopCart" => $shopCart]);
        return $this->fetch();
    }

    /**
     * 用户信息更新(完成)
     */
    public function update()
    {
        if (request()->isPost()) {
            $id = input('id');
            $data = [
                'user_name' => input('user_name'),
                'email' => input('email'),
                'phone' => input('phone'),
                'real_name' => input('real_name'),
            ];
            //真是姓名预先填写
            $data1 = [
                'user_name' => input('user_name'),
                'email' => input('email'),
                'phone' => input('phone'),
            ];
            $user11 = new \app\index\model\User;
            if (input('real_name')) {
//                dd(1);
//                $res = $user11->save($data, ['id' => $id]);
                $res=\app\index\model\User::where('id',$id)->update($data);
            } else {
//                dd(12);
//                $res = $user11->save($data1, ['id' => $id]);
                $res=\app\index\model\User::where('id',$id)->update($data1);
            }
            if ($res) {
                $this->success('修改成功');
            } else {
                $this->error('修改失败');
            }
        }
        $this->error('未知错误');
    }

    /**
     * 用户评论
     */
    public function comments()
    {
        $comments = Comments::where('user_id', session('uid'))
            ->with('goods')
            ->select();
//        dd($comments);
//        return jj($comments);
        $event = \think\Loader::controller('Goods', 'widget');

        //获取分类
        $result = Db('type')
            ->where("pid=0")
            ->limit(2)
            ->select();
        $type = $this->getType($result);
        View::share('type', $type);

        $shopCart = $event->topHeader();
        return view('User/comments', ['shopCart' => $shopCart,
            'comments' => $comments]);
    }


    /**
     * 收货地址--列表
     */
    public function address()
    {
        $address = Address::where('user_id', session('uid'))
            ->select();

        //一级行政区 省
        $province = Regions::where('father_id', null)->select();
        $event = \think\Loader::controller('Goods', 'widget');
        //获取分类
        $result = Db('type')
            ->where("pid=0")
            ->limit(2)
            ->select();
        $type = $this->getType($result);
        View::share('type', $type);

        $shopCart = $event->topHeader();
        return view('address', ['address' => $address,
            'province' => $province,
            'shopCart' => $shopCart]);
    }

    /**
     * 收货地址--修改
     */
    public function addressDel()
    {
        $id = input('id');
        $res = Address::destroy($id);
        if ($res)
            $this->success('删除成功');
        else
            $this->error('删除失败');

    }

    /**
     * 收货地址--设为默认地址
     */
    public function addressDefault()
    {
        $id = input('id');
        $default = Address::where(['type' => 1,
            'user_id' => session('uid')])
            ->find()
            ->toArray();

        if ($id == $default['id']) {
            echo json_encode(1);
        } else {
            Address::where(['type' => 1,
                'user_id' => session('uid')])->update([
                'type' => 0
            ]);
            $res = Address::where('id', $id)->update([
                'type' => 1
            ]);

            $success = $res ? 1 : 0;

            echo json_encode($success);

        }


    }

    /**
     *   收货地址-----保存、修改
     */

    public function saveAndUpdate()
    {
//       dump(input());
        $bool = in_array('on', input());
//       dd($bool);
        $address = new Address;
        if ($bool) {
            $res = $address->where(['user_id' => session('uid'),
                'type' => 1])
                ->update(['type' => 0]);
            if ($res)
                $res1 = $address->data([
                    'address_name' => input('address'),
                    'phone' => input('phone'),
                    'recipient' => input('recipient'),
                    'region_id' => input('county'),
                    'user_id' => session('uid'),
                    'type' => 1
                ])->save();
            if ($res1)
                $this->success('保存成功');
            $this->error('保存失败');
        } else {
            $res1 = $address->data([
                'address_name' => input('address'),
                'phone' => input('phone'),
                'recipient' => input('recipient'),
                'region_id' => input('county'),
                'user_id' => session('uid'),
                'type' => 0
            ])->save();
            if ($res1)
                $this->success('保存成功');
            $this->error('保存失败');
        }


    }

    //获取二级城市
    public function city()
    {
        $province = $_POST['province'];
        $city = Regions::where('father_id', $province)->select();

        return $city;
    }

    //获取三级城市
    public function county()
    {
        $id = $_POST['county'];
        $county = Regions::where('father_id', $id)->select();
        return $county;
    }

    /**
     * 核对订单页--保存收货地址
     */
    public function saveAddress()
    {
        $recipient = $_POST['recipient'];
        $address_name = $_POST['address_name'];
        $phone = $_POST['phone'];
        $region = $_POST['region'];

        $res = new Address;

        $res->address_name = $address_name;
        $res->phone = $phone;
        $res->recipient = $recipient;
        $res->region_id = $region;
        $res->user_id = session('uid');
        $res->type = 0;
        $res->save();
        $address_id = $res->id;

        if ($address_id) {
            $success = 1;
        } else {
            $success = 0;
        }

        echo json_encode($success, JSON_UNESCAPED_UNICODE);
    }

    public function test()
    {
//        dump(cache('qqq'));
//        $arr1 = [];
//        $arr = explode(" ", cache('qqq'));
//        dump($arr);
//        for ($i = 0; $i < count($arr); $i++) {
//            if ($arr[$i] !== "")
//                array_push($arr1, $arr[$i]);
//
//        }
//        dd($arr1);
//
        $shopCart = ShopCart::where(['order_id' => null,
            'user_id' => session('uid')])
            ->limit(4)
            ->select();
        dd($shopCart);
        $arr = [];
//        dd(cache('count'.session('uid')));
        for ($i = 0; $i < cache('count' . session('uid')); $i++) {
            array_push($arr, cache('shopCart' . $i . session('uid')));  //order表物品id
        }
//       array_push($arr,cache( 'address_id'.session('uid')));  //新增地址ID
        array_push($arr, cache('sum' . session('uid')));  //获取总金额
        dd($arr);
    }

    /**
     * 提交订单----保存支付方式  收货人
     */
    public function savePay()
    {

        $address = $_POST['address'];
        $pay = $_POST['pay'];
        $arr1 = [];
        $arr2 = [];
        $arr = explode(" ", $address);
//        dump($arr);
        for ($i = 0; $i < count($arr); $i++) {
            if ($arr[$i] !== "")
                array_push($arr1, $arr[$i]);
        }
        for ($i = 2; $i < 6; $i++) {
            array_push($arr2, $arr1[$i]);
        }
        $add = implode(" ", $arr2);   //地址
        $num = count($arr1);
        $addressId = Address::where([
            'phone' => $arr1[$num - 1],
            'address_name' => $add,
            'recipient' => $arr1[$num - 6],
        ])->field('id')
            ->find();
        $orderNum = new OrderNum;
        $orderNum->data([
            'order_num' => createdNumber(),
            'address_id' => $addressId['id'],
            'sum_price' => cache("sum" . session('uid')),
            'user_id' => session('uid'),
            'status' => 0,
            'pay_type' => $pay == '货到付款' ? 0 : 1,
            'time' => date("Y-m-d H:i:s", time())
        ]);

        $success = $orderNum->save();
        if ($success) {
            $orderNumId = $orderNum->id;
//           json_encode($ordeeNumId, JSON_UNESCAPED_UNICODE);
        } else {
            $orderNumId = 0;
//           echo json_encode(0, JSON_UNESCAPED_UNICODE);
        }
        echo json_encode($orderNumId, JSON_UNESCAPED_UNICODE);
    }
}
